package cn.ipanel.bigdata.boot.date

import java.util.Calendar

/**
 * Author: lzz
 * Date: 2021/11/22 18:44
 */
case class Week(st: Long, et: Long) extends Date(st, et) {

  override def prev(n: Int = 1): Week = Week(st - Date.WEEK_DAY_TIME * n)
  override def next(n: Int = 1): Week = Week(et + Date.WEEK_DAY_TIME * n - Date.DAY_TIME + 1)

  lazy final val minDayWeek: Int = 0
  lazy final val maxDayWeek: Int = 6
  lazy final val lenDayWeek: Int = maxDayWeek + 1

  def getDay(n: Int): Day = {
    if (n < minDayWeek) Day(st)
    else if (n > maxDayWeek) Day(st + Date.DAY_TIME * maxDayWeek)
    else Day(st + Date.DAY_TIME * n)
  }

  /**
   * 获取本周在当年的序号）
   * @return
   */
  def getWeekInYear: Int = {
    val calendar: Calendar = Calendar.getInstance()
    calendar.setTimeInMillis(st)
    calendar.get(Calendar.WEEK_OF_YEAR)
  }

  override def toString: String = s"Week(${STime.toYYYYMMddHHmmss} To ${ETime.toYYYYMMddHHmmss})"
}

object Week {

  def unapply(time: Long): Option[(Long, Long)] = {
    val ca: java.util.Calendar = java.util.Calendar.getInstance()
    ca.setFirstDayOfWeek(Calendar.MONDAY)
    ca.setTime(new java.util.Date(time))
//    val startDay: Int = ca.getActualMinimum(java.util.Calendar.DAY_OF_WEEK)
//    ca.set(java.util.Calendar.DAY_OF_WEEK, startDay + 1)
    ca.set(java.util.Calendar.DAY_OF_WEEK, Calendar.MONDAY)
    ca.set(java.util.Calendar.HOUR_OF_DAY, 0)
    ca.set(java.util.Calendar.MINUTE, 0)
    ca.set(java.util.Calendar.SECOND, 0)
    ca.set(java.util.Calendar.MILLISECOND, 0)
    Some(ca.getTimeInMillis, ca.getTimeInMillis + Date.WEEK_DAY_TIME - 1)
  }

  def apply(yyyyMMdd: String): Week = apply(Time(yyyyMMdd))
  def apply(time: Time): Week = apply(time.time)
  def apply(time: Long): Week = time match {
    case Week(st, et) => Week(st, et)
    case _ => null
  }
}